import { ClassificationTreeNode, MediumInstanceInfo } from '@/api/classify/type'
import { reqMediumInstance } from '@/api/classify'

export type ClassityNode = {
  id: string
  classificationType: string
}
export type ClassificationType = {
  typeName: string
  count: number
}

export type StatisticObj = {
  name: string
  value: ClassificationType[]
  color: string
}

export const statisticClassifications = async (
  data: ClassificationTreeNode[],
  parentCity: string,
  childCity: string
): Promise<StatisticObj[]> => {
  return reqMediumInstance().then((res) => {
    const instances: MediumInstanceInfo[] = res.data

    // 统计小类实例化情况，并记录被实例化的小类所属的中类
    const medium_instanced_set: Set<string> = new Set<string>()

    let smallTotalCount = 0
    let smallInstanceCount = 0

    for (const instance of instances) {
      if (instance.instancedCount > 0) {
        medium_instanced_set.add(instance.parentCode)
      }
      smallTotalCount += instance.totalCount
      smallInstanceCount += instance.instancedCount
    }

    // 统计大类和中类被实例化的情况

    data.sort((a, b) => a.classificationCode.localeCompare(b.classificationCode))

    let idx = 0

    let bigTotalCount = 0
    let bigInstanceCount = 0
    let mediumTotalCount = 0
    let mediumInstanceCount = 0

    while (idx < data.length) {
      if (data[idx].classificationType === '大类') {
        idx++
        let instanced = false
        while (idx < data.length && data[idx].classificationType === '中类') {
          if (medium_instanced_set.has(data[idx].classificationCode)) {
            instanced = true
            mediumInstanceCount++
          }
          mediumTotalCount++
          idx++
        }
        if (instanced) {
          bigInstanceCount++
        }
        bigTotalCount++
      }
    }

    const statistic_obj: StatisticObj[] = [
      {
        name: parentCity,
        value: [],
        color: '#f56c6c'
      },
      {
        name: childCity,
        value: [],
        color: '#409eff'
      }
    ]

    for (const key in statistic_obj) {
      statistic_obj[key].value = [
        {
          typeName: '大类',
          count: parseInt(key) % 2 === 0 ? bigTotalCount : bigInstanceCount
        },
        {
          typeName: '中类',
          count: parseInt(key) % 2 === 0 ? mediumTotalCount : mediumInstanceCount
        },
        {
          typeName: '小类',
          count: parseInt(key) % 2 === 0 ? smallTotalCount : smallInstanceCount
        }
      ]
    }

    return statistic_obj
  })
}
